package com.rwy.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.rwy.dao.UserManageDaoMapper;
import com.rwy.dto.user.UserDTO;
import com.rwy.util.CollectionUtil;
import com.rwy.util.PredicateUtil;
@Service
public class UserManageService {
	@Autowired
	UserManageDaoMapper userDao;

	public UserDTO getUserMesByopenID(String openID) {
		Assert.notNull(openID);;
		return userDao.getBusinessPartnerMesByOpenID(openID);
	}

	public UserDTO getBusinessPartnerByMObile(String mobile) {
		Assert.notNull(mobile);
		UserDTO user = userDao.getBusinessPartnerByMObile(mobile);

		if (!PredicateUtil.isEmpty(user) && !PredicateUtil.isEmpty(user.getBusinessPartnerID())) {
			user.buildpartnerIds(getChildID(user.getBusinessPartnerID()));
		}
		return user;
	}

	private List<Integer> getChildID(Integer parentId) {
		Assert.notNull(parentId);
		List<Integer> result = new ArrayList<Integer>();
		
		List<Integer> childIds = userDao.getChildPartnerIDByParentID(parentId);
		if (!CollectionUtil.isEmpty(childIds)) {
			result.addAll(getChildNode(childIds));
		}
		result.add(parentId);
		return result;
	}

	private List<Integer> getChildNode(List<Integer> source) {
		List<Integer> ids = new ArrayList<Integer>();
		for (Integer dd : source) {
			ids.add(dd);
			List<Integer> childIds = userDao.getChildPartnerIDByParentID(dd);
			if (CollectionUtil.isEmpty(childIds)) {
				continue;
			} ;
			ids.addAll(getChildNode(childIds));
		}
		return ids;
	}

}
